/** @format */

const express = require("express");

const router = express.Router();
const sqlFn = require("./mysql");
const axios = require("axios");
const jwt = require("jsonwebtoken");
const config = require("./secert");
// 引入图片模块
const multer = require("multer");
const fs = require("fs");
const { QRCode } = require("antd");

router.get("/", (req, res) => {
    res.send("首页加载成功");
});

router.post("/api/Cat", (req, res) => {
    axios
        .get(
            "https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E9%87%8D%E5%BA%86&ci=45&channelId=4"
        )
        .then((cat) => {
            res.send(cat.data);
        });
});

router.post("/api/quadratic", (req, res) => {
    axios.get("https://api.gmit.vip/Api/DmImg?return=json").then((ctx) => {
        res.send(ctx.data);
    });
});

router.post("/api/quick", (req, res) => {
    axios
        .get("https://api.gmit.vip/Api/KuaiShou?format=json&url=https://v.kuaishou.com/5Z8PbZ")
        .then((ctx) => {
            res.send(ctx.data);
        });
});

router.get("/api/goods", (req, res) => {
    const page = req.query.page || 1;
    const sql1 = `select * from goodlist where id`;
    sqlFn(sql1, null, (data) => {
        let len = data.length;
        let current = 4;
        const sql2 =
            "select * from goodlist order by id asc limit 4 offset 0" + (page - 1) * current;
        sqlFn(sql2, null, (result) => {
            if (result.length > 0) {
                res.send({
                    status: 200,
                    info: result,
                    pageSize: current,
                    total: len,
                });
            } else {
                res.send({
                    status: 500,
                    msg: "暂无数据",
                });
            }
        });
    });
});

router.post("/api/login", (req, res) => {
    const { account, passwd } = req.body;

    // console.log(req.body);

    const sql = "select * from admin where account=? and passwd=?";

    const arr = [account, passwd];

    // res.send('请求成功')
    sqlFn(sql, arr, (result) => {
        if (result.length > 0) {
            let token = jwt.sign(
                {
                    account: result[0].account,
                    id: result[0].id,
                },
                config.jwtSecert,
                {
                    expiresIn: 20 * 1,
                }
            );
            res.send({
                msg: "登陆成功",
                status: 200,
                token,
            });
        } else {
            res.send({
                status: 402,
                msg: "账号或密码错误",
            });
        }
    });
});

let logo = null;

function qr(name) {
    return name;
}

/**图片上床  */
Upload(); 

function Upload() {
    const uploadFolder = "./upload/";

    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, uploadFolder);
        },
        filename: function (req, file, cb) {
            cb(null, Date.now() + "-" + file.originalname);
        },
    });

    const createFolder = function (folder) {
        try {
            fs.accessSync(folder);
        } catch (e) {
            fs.mkdirSync(folder);
        }
    };

    createFolder(uploadFolder);

    const upload = multer({
        storage: storage,
    });

    function jpeg(data, name) {
        name = `D:/Web_Study/web大前端/vue_2/Queen-honey/server/upload/${data}`;
        logo = name;
        qr(name);
    }

    function uploading(req, res, name) {
        const file = req.file;
        res.json({
            res_code: "200",
            name: file.originalname,
            url: file.path,
        });
        const str = file.path.slice(7);
        jpeg(str, name);
    }

    router.post("/api/upload", upload.single("file"), (req, res) => {
        uploading(req, res, logo);
    });

    router.post("/api/qr", upload.single("file"), (req, res) => {
        uploading(req, res, qr());
    });
}

/** 表单信息添加 */
router.post("/api/message", (req, res) => {
    const {
        site_title,
        site_url,
        site_description,
        site_copyight,
        company_email,
        company_weixin,
        company_address,
        site_keywords,
        company_name,
        company_phone,
        company_qq,
    } = req.body;

    // 这里的字段一定要与数据库的一样 不然报错 第一个id 默认为null
    const sql = `insert into web_base values (null,?,?,?,?,?,?,?,?,?,?,?,?,?)`;

    const arr = [
        site_title || "",
        site_url || "",
        logo || "",
        site_description || "",
        site_copyight || "",
        company_email || "",
        company_weixin || "",
        qr() || "",
        company_address || "",
        site_keywords || "",
        company_name || "",
        company_phone || "",
        company_qq || "",
    ];

    sqlFn(sql, arr, (result) => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "保存成功",
            });
        } else {
            res.send({
                status: 500,
                msg: "保存失败",
            });
        }
    });
});

/** 用户列表 */

router.get("/api/userlist", (req, res) => {
    const sql = "SELECT * FROM admin WHERE 1";
    sqlFn(sql, null, (result) => {
        res.send(result);
    });
});

router.post("/api/admin", (req, res) => {
    const { account, passwd } = req.body;

    const sql = "SELECT * FROM admin WHERE account = ?";

    const sql2 = `INSERT INTO admin VALUES (null,?,?)`;

    const arr = [account, passwd];

    sqlFn(sql, [account], (result1) => {
        if (result1.length >= 1) {
            return res.send({
                status: 401,
                msg: "该用户已存在",
            });
        } else {
            sqlFn(sql2, arr, (result2) => {
                if (result2.affectedRows > 0) {
                    res.send({
                        status: 200,
                        msg: "添加成功",
                    });
                } else {
                    res.send({
                        status: 403,
                        msg: "添加失败",
                    });
                }
            });
        }
    });
});

router.post("/api/userDel", (req, res) => {
    const { id } = req.body;

    const sql = `DELETE FROM admin WHERE id=?`;

    sqlFn(sql, [id], (result) => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "删除成功",
            });
        } else {
            res.send({
                status: 500,
                msg: "删除失败",
            });
        }
    });
});

router.post("/api/userUpload", (req, res) => {

    let id = req.body[0]; 

    const { account, passwd } = req.body[1];

    const sql = `update admin set account=?, passwd=? where id=?`; 

    let arr = [account, passwd,id];

    sqlFn(sql, arr, (result) => {
        // console.log(result)
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "修改成功",
            });
        } else {
            res.send({
                status: 500,
                msg: "修改失败",
            });
        }
    });
});

router.post("/api/enter", (req, res) => {
    res.send("666");
});

module.exports = router;


